package com.jie.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.jie.eduservice.entity.EduSubject;
import com.jie.eduservice.entity.excel.SubjectData;
import com.jie.eduservice.entity.vo.SubjectVO;
import com.jie.eduservice.listener.SubjectExcelListener;
import com.jie.eduservice.mapper.EduSubjectMapper;
import com.jie.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author xzj
 * @since 2020-10-08
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file) {
        try {
            // 1.获取文件的输入流
            InputStream in = file.getInputStream();
            // 2.调用方法j进行读取
            EasyExcel.read(in, SubjectData.class, new SubjectExcelListener(this)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 此方法我与老师的实现不同
    @Override
    public List<SubjectVO> getAllSubjects() {

        // 0.创建一个返回的list集合
        List<SubjectVO> subjectVOS = new ArrayList<>();

        // 1.查询所有的分类
        List<EduSubject> eduSubjects = baseMapper.selectList(null);

        // 2.存入map中(方便循环的时候找父节点, 然后直接把子节点放入父节点中)
        Map<String, SubjectVO> map = new HashMap<>();
        List<SubjectVO> subjectVOList = new ArrayList<>();
        for (EduSubject eduSubject : eduSubjects) {
            SubjectVO subjectVO = new SubjectVO();
            BeanUtils.copyProperties(eduSubject, subjectVO);
            map.put(subjectVO.getId(), subjectVO);
            subjectVOList.add(subjectVO);
        }

        // 3.建立树形结构
        for (SubjectVO subjectVO : subjectVOList) {
            if ("0".equals(subjectVO.getParentId())) {  // 如果pid为0则代表是第一级
                subjectVOS.add(subjectVO);
                continue;
            }
            // 把自己添加到父节点的孩子中
            SubjectVO tempSubject = map.get(subjectVO.getParentId());
            if (tempSubject != null) {
                tempSubject.getChildren().add(subjectVO);
            }
        }

        return subjectVOS;
    }

}
